package org.jeecg.modules.demo.base.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.analysis.entity.ZnzfTurn;
import org.jeecg.modules.demo.analysis.service.IZnzfTurnService;
import org.jeecg.modules.demo.base.entity.ZnzfEmployee;
import org.jeecg.modules.demo.base.entity.ZnzfEmployeeRoomInfoParam;
import org.jeecg.modules.demo.base.service.IZnzfEmployeeService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.projectroom.entity.ZnzfRoom;
import org.jeecg.modules.demo.projectroom.service.IZnzfRoomService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 职工表
 * @Author: jeecg-boot
 * @Date:   2022-03-27
 * @Version: V1.0
 */
@Api(tags="职工表")
@RestController
@RequestMapping("/base/znzfEmployee")
@Slf4j
public class ZnzfEmployeeController extends JeecgController<ZnzfEmployee, IZnzfEmployeeService> {
	@Autowired
	private IZnzfEmployeeService znzfEmployeeService;

	 @Autowired
	 private ISysUserService sysUserService;

	 @Autowired
	 private IZnzfRoomService znzfRoomService;

     @Autowired
     private IZnzfTurnService znzfTurnService;
	
	/**
	 * 分页列表查询
	 *
	 * @param znzfEmployee
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "职工表-分页列表查询")
	@ApiOperation(value="职工表-分页列表查询", notes="职工表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ZnzfEmployee>> queryPageList(ZnzfEmployee znzfEmployee,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZnzfEmployee> queryWrapper = QueryGenerator.initQueryWrapper(znzfEmployee, req.getParameterMap());
		Page<ZnzfEmployee> page = new Page<ZnzfEmployee>(pageNo, pageSize);
		IPage<ZnzfEmployee> pageList = znzfEmployeeService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param znzfEmployee
	 * @return
	 */
	@AutoLog(value = "职工表-添加")
	@ApiOperation(value="职工表-添加", notes="职工表-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ZnzfEmployee znzfEmployee) {
		znzfEmployee = znzfEmployeeToSysUser(znzfEmployee);
		znzfEmployeeService.save(znzfEmployee);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param znzfEmployee
	 * @return
	 */
	@AutoLog(value = "职工表-编辑")
	@ApiOperation(value="职工表-编辑", notes="职工表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ZnzfEmployee znzfEmployee) {
		znzfEmployeeService.updateById(znzfEmployee);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "职工表-通过id删除")
	@ApiOperation(value="职工表-通过id删除", notes="职工表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		znzfEmployeeService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "职工表-批量删除")
	@ApiOperation(value="职工表-批量删除", notes="职工表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.znzfEmployeeService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "职工表-通过id查询")
	@ApiOperation(value="职工表-通过id查询", notes="职工表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ZnzfEmployee> queryById(@RequestParam(name="id",required=true) String id) {
		ZnzfEmployee znzfEmployee = znzfEmployeeService.getById(id);
		if(znzfEmployee==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(znzfEmployee);
	}

	 /**
	  * 通过userId查询我的住房信息
	  *
	  * @param userId
	  * @return
	  */
	 @ApiOperation(value="职工表-通过userId查询我的信息", notes="职工表-通过userId查询我的信息")
	 @GetMapping(value = "/queryMyRoomInfoByUserId")
	 public Result<ZnzfEmployeeRoomInfoParam> queryMyRoomInfoByUserId(@RequestParam(name="userId",required=true) String userId) {
		 ZnzfEmployeeRoomInfoParam znzfEmployeeRoomInfoParam = znzfEmployeeService.queryMyRoomInfoByUserId(userId);
		 if(oConvertUtils.isEmpty(znzfEmployeeRoomInfoParam)) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(znzfEmployeeRoomInfoParam);
	 }

     /**
      * 通过token查询轮候排名
      * @param request
      * @return
      */
     @ApiOperation(value="职工表-通过token查询轮候排名", notes="职工表-通过token查询轮候排名")
     @GetMapping(value = "/queryMyTurn")
     public Result<ZnzfTurn> queryMyTurn(HttpServletRequest request) {
         String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
         String name = JwtUtil.getUsername(token);
         SysUser sysUser = sysUserService.getUserByName(name);
         if(oConvertUtils.isEmpty(sysUser))
             return Result.error("账号异常");
         ZnzfEmployee znzfEmployee = znzfEmployeeService.searchByUid(sysUser.getId());
         if(oConvertUtils.isEmpty(znzfEmployee))
             return Result.error("职工信息异常");
         ZnzfTurn znzfTurn = znzfTurnService.searchByEmployeeId(znzfEmployee.getId());
         if(oConvertUtils.isEmpty(znzfTurn))
             return Result.error("无轮候信息");
         return Result.OK(znzfTurn);
     }


     /**
    * 导出excel
    *
    * @param request
    * @param znzfEmployee
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZnzfEmployee znzfEmployee) {
        return super.exportXls(request, znzfEmployee, ZnzfEmployee.class, "职工表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		Result<?> res = super.importExcel(request, response, ZnzfEmployee.class);
		if(res.getCode().equals(CommonConstant.SC_OK_200)){
			List<ZnzfEmployee> employeeList = (List<ZnzfEmployee>) res.getResult();
			for(ZnzfEmployee znzfEmployee : employeeList){
				znzfEmployee = znzfEmployeeToSysUser(znzfEmployee);
				znzfEmployeeService.updateById(znzfEmployee);
			}
		}
        return res;
    }


	 /**
	  * 通过userId查询
	  *
	  * @param userId
	  * @return
	  */
	 //@AutoLog(value = "职工表-通过userId查询")
	 @ApiOperation(value="职工表-通过userId查询", notes="职工表-通过userId查询")
	 @GetMapping(value = "/searchByUid")
	 public Result<ZnzfEmployee> searchByUid(@RequestParam(name="userId",required=true) String userId) {
		 ZnzfEmployee znzfEmployee = znzfEmployeeService.searchByUid(userId);
		 if(znzfEmployee==null) {
			 return Result.error("未找到对应数据",null);
		 }
		 return Result.OK(znzfEmployee);
	 }

	 /**
	  * 查询用户是否有房源
	  *
	  * @param
	  * @return
	  */
	 //@AutoLog(value = "职工表-查询用户是否有房源")
	 @ApiOperation(value="职工表-查询用户是否有房源", notes="职工表-查询用户是否有房源")
	 @PostMapping(value = "/hasRoom")
	 public Result<ZnzfRoom> hasRoom(HttpServletRequest request) {
		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String name = JwtUtil.getUsername(token);
		 SysUser sysUser = sysUserService.getUserByName(name);
		 if(sysUser == null)
		 	return Result.error("账号异常");
		 ZnzfEmployee znzfEmployee = znzfEmployeeService.searchByUid(sysUser.getId());
		 if(znzfEmployee==null) {
			 return Result.error("未找到对应数据",null);
		 }
		 if(oConvertUtils.isEmpty(znzfEmployee.getRoomId()))
		 	return Result.error("未有房源");
		 return Result.OK(znzfRoomService.getById(znzfEmployee.getRoomId()));
	 }

	 public ZnzfEmployee znzfEmployeeToSysUser(ZnzfEmployee znzfEmployee){
		 SysUser user = new SysUser();
		 user.setPhone(znzfEmployee.getTel());
		 user.setRealname(znzfEmployee.getName());
		 user.setSex(znzfEmployee.getSex());
		 user.setUsername(znzfEmployee.getTel());
		 user.setPassword("888888");
		 user.setStatus(1);
		 user.setDelFlag(0);
		 if(oConvertUtils.isNotEmpty(znzfEmployee.getNo()))
			 user.setWorkNo(znzfEmployee.getNo());
		 user.setPost("职工");
		 user.setUserIdentity(1);
		 user.setAvatar("https://static.jeecg.com/temp/jmlogo_1606575041993.png");
		 String selectedRoles = "1169504891467464705"; //TODO 默认第三方  之后修改
		 String selectedDeparts = ""; //TODO 部门？
		 user.setCreateTime(new Date());//设置创建时间
		 String salt = oConvertUtils.randomGen(8);
		 user.setSalt(salt);
		 String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
		 user.setPassword(passwordEncode);
		 user.setStatus(1);
		 user.setDelFlag(CommonConstant.DEL_FLAG_0);
		 // 保存用户走一个service 保证事务
		 sysUserService.saveUser(user, selectedRoles, selectedDeparts);
		 znzfEmployee.setUserId(user.getId());
		 return znzfEmployee;
	 }
}
